package com.henu.acmrating.crawler;

import com.henu.acmrating.pojo.Problem;
import com.henu.acmrating.pojo.UserOj;
import com.henu.acmrating.service.ProblemService;
import com.henu.acmrating.service.UserOjService;
import com.henu.acmrating.utils.DateUtils;
import com.henu.acmrating.utils.StringUtils;
import com.henu.acmrating.webmagic.SeleniumDownloader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

@Component
public class LOJProcessor implements PageProcessor {

    private static final String OJ_NAME = "LOJ";
    private static final String BASE_URL = "https://loj.ac/s?submitter=";

    @Resource
    UserOjService userOjService;

    @Resource
    ProblemService problemService;

    public static LOJProcessor lojProcessor;

    @PostConstruct
    public void init() {
        lojProcessor = this;
    }

    @Override
    public void process(Page page) {
        Html html = page.getHtml();
        String account = StringUtils.getParam(page.getUrl().toString(), "submitter");
        List<Selectable> nodes = html.xpath("//table/tbody/tr").nodes();
        if (nodes.size() == 0) return;
        UserOj userOj = lojProcessor.userOjService.selectByAccountAndOjName(account, OJ_NAME);
        int lastId = userOj.getLastId();

        int maxRunId = 0;
        // 标记是否继续爬虫下一页
        boolean flag = true;
        List<Problem> problemList = new LinkedList<>();
        Set<String> acProblemSet = new HashSet<>();
        for (Selectable item : nodes) {
            Problem problem = new Problem(
                    userOj.getUserId(), OJ_NAME,
                    item.xpath("//tr/td[1]/a/@href").toString().substring(3),
                    item.xpath("//tr/td[3]/div[1]/allText()").toString(),
                    item.xpath("//tr/td[3]/div[1]/a").links().toString(),
                    DateUtils.getDateByString(item.xpath("//tr/td[7]/@title").toString()),
                    item.xpath("//tr/td[1]/allText()").toString(),
                    item.xpath("//tr/td[6]/span/a/allText()").toString(),
                    item.xpath("//tr/td[5]/allText()").toString(),
                    item.xpath("//tr/td[4]/allText()").toString()
            );
            // 结束爬虫 （没有数据的时候
            if (problem.getSubmitTime() == null) {
                flag = false;
                break;
            }
            int nowRunId = Integer.parseInt(problem.getRunId());

            maxRunId = Math.max(maxRunId, nowRunId);
            if (nowRunId == lastId) {
                flag = false;
                break;
            }
            problemList.add(problem);

            if (BaseProcessor.isContain(problem.getSubmitStatus())) {
                acProblemSet.add(problem.getProblemUrl());
            }
        }
        BaseProcessor.insertDataBase(lojProcessor.problemService, userOj, acProblemSet, problemList, maxRunId, lojProcessor.userOjService);

        if (flag) {
            String url = html.xpath("//a[contains(@class,\"icon\") and contains(@class,\"item\") and contains(@type, \"nextItem\")  and contains(@aria-disabled,\"false\")]").links().toString();
            if (url != null) {
                page.addTargetRequest(url);
            }
        }
    }

    private Site site = Site.me()
            .setTimeOut(15 * 1000)  // 设置超时时间
            .setRetrySleepTime(3000)// 设置重试的间隔时间
            .setRetryTimes(3);      // 设置重试次数

    @Override
    public Site getSite() {
        return site;
    }

    @Value("${prop.driver-path}")
    private String driverPath;

    @Scheduled(cron = "0 0 6 ? * * ")
    public void start() {
        Spider.create(new LOJProcessor())
                .addUrl(BaseProcessor.getUrls(userOjService, OJ_NAME, BASE_URL))
                .setDownloader(new SeleniumDownloader(driverPath))
                .thread(1)
                .start();
    }

    public static void run_all() {
        Spider.create(new LOJProcessor())
                .addUrl(BaseProcessor.getUrls(lojProcessor.userOjService, OJ_NAME, BASE_URL))
                .setDownloader(new SeleniumDownloader(lojProcessor.driverPath))
                .thread(1)
                .start();
    }

    public static void run(String id) {
        Spider.create(new LOJProcessor())
                .addUrl(BASE_URL + id)
                .setDownloader(new SeleniumDownloader(lojProcessor.driverPath))
                .thread(1)
                .start();
    }

    public static void main(String[] args) {
        Spider.create(new LOJProcessor())
                .addUrl(BASE_URL + "henuly")
                .setDownloader(new SeleniumDownloader("F:/chromedriver_win32/chromedriver.exe"))
                .thread(1)
                .start();
    }
}
